package com.tianma.upload.uploadjartest.socket.udp.demo02;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author lgc
 * @createDate 2020/8/18 - 9:04
 */
public class TalkSend implements Runnable{
    private String toIp;
    private Integer toPort;
    private String fromName;
    private DatagramSocket socket;
    private BufferedReader br;

    public TalkSend(String toIp, Integer toPort,String fromName) {
        this.toIp = toIp;
        this.toPort = toPort;
        this.fromName = fromName;
        try {
            socket = new DatagramSocket();
            br = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        try {
            while (true){
                String line =fromName+":"+br.readLine();
                byte[] bytes = line.getBytes();
                DatagramPacket data = new DatagramPacket(bytes,0,bytes.length, InetAddress.getByName(toIp),toPort);
                socket.send(data);
                if ("bye".equals(line)){
                    break;
                }
            }

            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
